package com.qingmu.club.minaapi.controller.club;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qingmu.club.minaapi.custom.logic.ClubUsersLogic;
import com.qingmu.club.minaapi.custom.logic.PushMessageLogic;
import com.qingmu.club.minaapi.custom.logic.UsersWxLogic;
import com.qingmu.club.minaapi.enums.MagicGroupStatusEnum;
import com.qingmu.club.minaapi.plus.entity.*;
import com.qingmu.club.minaapi.plus.service.*;
import com.qingmu.club.minaapi.utils.KeyValueDefine;
import com.qingmu.club.minaapi.utils.ResponseObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.qingmu.club.minaapi.enums.MagicGroupStatusEnum;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@Api(value = "扫码扣积分相关(俱乐部端小程序)", description = "扫码扣积分相关（俱乐部端小程序）")
@CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.GET})
@RequestMapping("/club/readCode")
public class ClubReadQRCodeController {

    @Autowired
    ClubStaffShopService clubStaffShopService;

    @Autowired
    OrderInfoService orderInfoService;

    @Autowired
    ClubStaffService clubStaffService;

    @Autowired
    ClubUsersService clubUsersService;

    @Autowired
    ClubUsersIntegralService clubUsersIntegralService;

    @Autowired
    UsersWxLogic usersWxLogic;

    @Autowired
    IntegralGoodsService integralGoodsService;

    @Autowired
    CourseService courseService;

    @Autowired
    MagicGroupRunService magicGroupRunService;

    @Autowired
    MagicGroupRuleService magicGroupRuleService;

    @Autowired
    MagicGroupJoinlistService magicGroupJoinlistService;

    @Autowired
    MagicGroupService magicGroupService;

    @Autowired
    UsersService usersService;

    @Autowired
    ClubUsersLogic clubUsersLogic;

    @Autowired
    ClubUsersCourseService clubUsersCourseService;

    @Autowired
    PushMessageLogic pushMessageLogic;

    @Autowired
    PushMessageService pushMessageService;

    @RequestMapping(value = "/readQRCode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "扫商品二维码")
    public ResponseEntity readQRCode(
            @ApiParam(required = true, value = "俱乐部人员ID") @RequestParam(required = true) String staffId,
            @ApiParam(required = true, value = "会员id") @RequestParam(required = true) String userId,
            @ApiParam(required = false, value = "门店id") @RequestParam(required = false) String shopId,
            @ApiParam(required = true, value = "二维码id") @RequestParam(required = true) String codeId,
            @ApiParam(required = false, value = "积分商品id") @RequestParam(required = false) String goodsId,
            @ApiParam(required = true, value = "二维码类型(0-积分商品 1-魔力拼团)") @RequestParam(required = true) Integer codeType,
            @ApiParam(required = false, value = "魔力拼团运行数据id") @RequestParam(required = false) String runId,
            @ApiParam(required = false, value = "课程id") @RequestParam(required = false) String courseId

    ) {

        ClubStaff clubStaff = this.usersWxLogic.getClubStaff(staffId);
        if (clubStaff == null) {
            return ResponseObject.error(401, "身份信息出错");
        }
        QueryWrapper queryWrapper = new QueryWrapper<>().eq(OrderInfo.CODE_ID, codeId);
        OrderInfo oneOrder = this.orderInfoService.getOne(queryWrapper);
        if (oneOrder != null) {
            return ResponseObject.error(557, "请勿重复兑换或核销");
        }
//积分商品二维码核销
        if (codeType == 0) {

            IntegralGoods integralGoods = this.integralGoodsService.getById(goodsId);
            if (integralGoods == null) {
                return ResponseObject.error(559, "积分商品不存在");
            }
            if (integralGoods.getGoodsNum() == 0) {
                return ResponseObject.error(560, "积分商品数量不够");
            }
            if (integralGoods.getLimitTimes() == 0) {
                return ResponseObject.error(561, "兑换次数已兑完");
            }
            Users users = this.usersService.getById(userId);
            QueryWrapper queryWrapper2 = new QueryWrapper<>()
                    .eq(ClubStaffShop.STAFF_ID, staffId)
                    .eq(ClubStaffShop.SHOP_ID, shopId)
                    .in(ClubStaffShop.STAFF_TAG,KeyValueDefine.ISCOACH,KeyValueDefine.ISCOUNSELOR,KeyValueDefine.ISSHOPOWNER)
                    .last("limit 1");
            ClubStaffShop clubStaffShop = this.clubStaffShopService.getOne(queryWrapper2);
            if (clubStaffShop == null) {
                return ResponseObject.error(549, "操作人员不是" + integralGoods.getShopName() + "门店相关工作人员");
            }

            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setUserId(userId);
            orderInfo.setClubUsersName(users.getUserName());
            if (!StringUtils.isEmpty(users.getUserMobile())) orderInfo.setUserMobile(users.getUserMobile());
//            orderInfo.setUserMobile(users.getUserMobile());
            orderInfo.setShopId(shopId);
            orderInfo.setShopName(integralGoods.getShopName());
            orderInfo.setClubId(integralGoods.getClubId());
            orderInfo.setCodeId(codeId);
            orderInfo.setGoodsId(goodsId);
            orderInfo.setGoodsImage(integralGoods.getGoodsHomeImage());
            orderInfo.setGoodsName(integralGoods.getGoodsName());
            orderInfo.setCreateUserId(staffId);
            orderInfo.setCreateUserName(clubStaff.getStaffName());
            orderInfo.setExchangeNum(integralGoods.getGoodsPrice());
            orderInfo.setStatus(KeyValueDefine.ALREADY_CONVERT);

            //修改订单状态
            boolean orderInfo_status = this.orderInfoService.save(orderInfo);
            if (!orderInfo_status) {
                return ResponseObject.error(555, "订单生成失败");
            }

            //修改积分商品数量
            integralGoods.setGoodsNum(integralGoods.getGoodsNum() - 1);
            integralGoods.setGoodsNumOver(integralGoods.getGoodsNumOver() + 1);
            integralGoods.setLimitTimes(integralGoods.getLimitTimes() - 1);
            boolean integralGoods_status = integralGoodsService.updateById(integralGoods);
            if (!integralGoods_status) {
                return ResponseObject.error(555, "商品数量保存失败");
            }

            int sumJf = 0;
//        ClubUsers clubUsers = this.clubUsersService.getById(orderInfo.getUserId());
            QueryWrapper<ClubUsers> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq(ClubUsers.USER_ID, orderInfo.getUserId()).eq(ClubUsers.SHOP_ID, shopId);
            ClubUsers clubUsers = this.clubUsersService.getOne(queryWrapper1);
            if (clubUsers == null) {
                return ResponseObject.error(556, "会员不存在");
            }

            sumJf = clubUsers.getUserJf() - orderInfo.getExchangeNum();
            clubUsers.setUserJf(sumJf);

            boolean clubUsers_stats = this.clubUsersService.updateById(clubUsers);
            if (clubUsers_stats) {
                ClubUsersIntegral clubUsersIntegral = new ClubUsersIntegral();
                clubUsersIntegral.setClubUsersId(clubUsers.getId());
                clubUsersIntegral.setUserId(userId);
                clubUsersIntegral.setShopId(shopId);
                clubUsersIntegral.setCreateUserId(staffId);
                clubUsersIntegral.setCreateUserName(clubStaff.getStaffName());
                clubUsersIntegral.setIntegralNum(orderInfo.getExchangeNum());
                clubUsersIntegral.setType(KeyValueDefine.JF_CUT_DOWN);//积分减少
                clubUsersIntegral.setIntegralType(KeyValueDefine.JF_AUTO_CHANGE);//系统自动操作
                clubUsersIntegral.setGoodsImage(integralGoods.getGoodsHomeImage());
                clubUsersIntegral.setIntegralName(integralGoods.getGoodsName());
                clubUsersIntegral.setIntegralChangeType(KeyValueDefine.BUY_GOODS);//购买商品扣减积分
                boolean state = clubUsersIntegralService.save(clubUsersIntegral);
                if (!state) {
                    return ResponseObject.error(555, "积分记录生成失败");
                }
//                return ResponseObject.success();
            }

            //积分商品核销成功推送模板消息
            PushMessage pushMessage = this.pushMessageLogic.queryPushMessageList(userId);
            if(pushMessage!=null) {
                this.pushMessageLogic.sendJfExchangeTemplate(pushMessage.getOpenId(), pushMessage.getFormId(), integralGoods.getGoodsName(), integralGoods.getGoodsPrice(), clubUsers.getUserJf(), clubUsers.getShopName(), clubUsers.getApplyTime(), new Date());
                pushMessage.setIsUse(true);
                this.pushMessageService.updateById(pushMessage);
            }
        }

//魔力拼团二维码核销
        if (codeType == 1) {

            MagicGroupRun magicGroupRun = this.magicGroupRunService.getById(runId);
            if (magicGroupRun == null) {
                return ResponseObject.error(558, "拼团不存在");
            }
//            if(magicGroupRun.getIsClose()==1){
//                return ResponseObject.error(590, "对不起，此拼团不能重复核销");
//            }
            if (!magicGroupRun.getStatus().equals(MagicGroupStatusEnum.success.toString())) {
                return ResponseObject.error(557, "拼团未成功");
            }
//            MagicGroupRule magicGroupRule = this.magicGroupRuleService.getById(magicGroupRun.getGroupId());
            Course course = this.courseService.getById(courseId);
            if (course == null) {
                return ResponseObject.error(559, "拼团课程不存在");
            }
            MagicGroup magicGroup = this.magicGroupService.getById(magicGroupRun.getGroupId());
            QueryWrapper queryWrapper2 = new QueryWrapper<>()
                    .eq(ClubStaffShop.STAFF_ID, staffId)
                    .in(ClubStaffShop.STAFF_TAG, KeyValueDefine.ISCOACH,KeyValueDefine.ISCOUNSELOR,KeyValueDefine.ISSHOPOWNER)
                    .eq(ClubStaffShop.SHOP_ID, magicGroup.getShopId())
                    .last("limit 1");
            ClubStaffShop clubStaffShop = this.clubStaffShopService.getOne(queryWrapper2);
            if (clubStaffShop == null) {
                return ResponseObject.error(558, "操作人员不是" + course.getShopName() + "门店相关工作人员");
            }


                //反查用户的clubUsersId用于判断是否已经绑定该课程
                ClubUsers clubUsersCourseDecision = this.clubUsersService.getOne(new QueryWrapper<ClubUsers>()
                        .eq(ClubUsers.USER_ID, userId)
                        .eq(ClubUsers.SHOP_ID, magicGroup.getShopId())
                        .last("limit 1")
                );
                if (clubUsersCourseDecision != null){
                QueryWrapper<ClubUsersCourse> usersCourseQueryWrapper = new QueryWrapper<>();
                usersCourseQueryWrapper.lambda().eq(ClubUsersCourse::getCourseId, courseId).eq(ClubUsersCourse::getClubUsersId, clubUsersCourseDecision.getId());
                List<ClubUsersCourse> clubUsersCourses = this.clubUsersCourseService.list(usersCourseQueryWrapper);
                if (!CollectionUtils.isEmpty(clubUsersCourses)) {
                    return ResponseObject.error(605, "该会员已绑定课程:" + course.getCourseName() + "，请勿重复绑定");
                }
            }

            QueryWrapper<MagicGroupRule> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq(MagicGroupRule.GROUP_ID, magicGroupRun.getGroupId());
//                    .ge((magicGroupRun.getJoinQty() != null),MagicGroupRule.QTY_END,magicGroupRun.getJoinQty())
//                    .le((magicGroupRun.getJoinQty() != null),MagicGroupRule.QTY_BEGIN,magicGroupRun.getJoinQty());
            List<MagicGroupRule> magicGroupRuleList = magicGroupRuleService.list(queryWrapper1);
            //获取最优拼团进行核销
            int qtyBeginBest = magicGroupRuleList.get(0).getQtyBegin();
            for (MagicGroupRule magicGroupRuleOne : magicGroupRuleList) {
                if (magicGroupRuleOne.getQtyBegin() < qtyBeginBest) {
                    qtyBeginBest = magicGroupRuleOne.getQtyBegin();
                }
            }

            //获取该最优拼团的拼团规则
            QueryWrapper<MagicGroupRule> qw = new QueryWrapper<>();
            qw.eq(MagicGroupRule.GROUP_ID, magicGroupRun.getGroupId())
                    .eq(MagicGroupRule.QTY_BEGIN, qtyBeginBest)
                    .last("limit 1");
            MagicGroupRule magicGroupRule = this.magicGroupRuleService.getOne(qw);

            //魔力拼团核销增加订单信息
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setUserId(userId);
            orderInfo.setShopId(magicGroup.getShopId());
            orderInfo.setCodeId(codeId);
            orderInfo.setGoodsImage(course.getCourseImage());
            orderInfo.setGoodsName(course.getCourseName());
            orderInfo.setCreateUserId(staffId);
            orderInfo.setCreateUserName(clubStaff.getStaffName());
            orderInfo.setCoursePrice(course.getCoursePrice());
            orderInfo.setStatus(KeyValueDefine.ALREADY_CONVERT);
            orderInfo.setRunId(runId);
            orderInfo.setGroupId(magicGroupRun.getGroupId());
            orderInfo.setCourseId(courseId);
            orderInfo.setMasterDiscount(magicGroupRule.getMasterDiscount());
            orderInfo.setMasterJf(magicGroupRule.getMasterJf());
            orderInfo.setMemberDiscount(magicGroupRule.getMemberDiscount());
            orderInfo.setMemberJf(magicGroupRule.getMemberJf());


            int sumJf = 0;
            QueryWrapper queryWrapper4 = new QueryWrapper<>()
                    .eq(MagicGroupJoinlist.RUN_ID, runId)
                    .eq(MagicGroupJoinlist.USER_ID, userId);
            MagicGroupJoinlist magicGroupJoinlist = this.magicGroupJoinlistService.getOne(queryWrapper4);
            magicGroupJoinlist.setIsClose(1);

            QueryWrapper<ClubUsers> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq(ClubUsers.USER_ID, magicGroupJoinlist.getUserId()).eq(ClubUsers.SHOP_ID, magicGroup.getShopId());
            ClubUsers clubUsers = this.clubUsersService.getOne(queryWrapper3);
            if (clubUsers == null) {
                return ResponseObject.error(556, "该门店所属用户不存在");
            }

            if (magicGroupJoinlist.getIsLeader() == 1) {
                orderInfo.setExchangeNum(magicGroupRule.getMasterJf());
            } else if (magicGroupJoinlist.getIsLeader() == 0) {
                orderInfo.setExchangeNum(magicGroupRule.getMemberJf());
            }
            //修改订单状态
            boolean orderInfo_status = this.orderInfoService.save(orderInfo);
            if (!orderInfo_status) {
                return ResponseObject.error(555, "订单生成失败");
            }

            if (magicGroupJoinlist.getIsLeader() == 1) {
                sumJf = clubUsers.getUserJf() + magicGroupRule.getMasterJf();
                clubUsers.setUserJf(sumJf);
            } else if (magicGroupJoinlist.getIsLeader() == 0) {
                sumJf = clubUsers.getUserJf() + magicGroupRule.getMemberJf();
                clubUsers.setUserJf(sumJf);
            }

            //魔力拼图核销添加记录
            boolean clubUsers_stats = this.clubUsersService.updateById(clubUsers);
            if (clubUsers_stats) {
                ClubUsersIntegral clubUsersIntegral = new ClubUsersIntegral();
                clubUsersIntegral.setClubUsersId(clubUsers.getId());
                clubUsersIntegral.setUserId(userId);
                clubUsersIntegral.setShopId(magicGroup.getShopId());
                clubUsersIntegral.setCreateUserId(staffId);
                clubUsersIntegral.setCreateUserName(clubStaff.getStaffName());
                clubUsersIntegral.setType(KeyValueDefine.JF_ADD);//积分增加
                clubUsersIntegral.setIntegralType(KeyValueDefine.JF_AUTO_CHANGE);//系统自动操作
                clubUsersIntegral.setGoodsImage(course.getCourseImage());
                clubUsersIntegral.setIntegralName(course.getCourseName());
                clubUsersIntegral.setIntegralChangeType(KeyValueDefine.MAGIC);//魔力拼团送积

                if (magicGroupJoinlist.getIsLeader() == 1) {
                    clubUsersIntegral.setIntegralNum(magicGroupRule.getMasterJf());
                } else if (magicGroupJoinlist.getIsLeader() == 0) {
                    clubUsersIntegral.setIntegralNum(magicGroupRule.getMemberJf());
                }

                boolean state = clubUsersIntegralService.save(clubUsersIntegral);
                if (!state) {
                    return ResponseObject.error(555, "积分记录生成失败");
                }

                //更新拼团已核销状态
                this.magicGroupJoinlistService.updateById(magicGroupJoinlist);


            }
            //没有关注门店则自动关注门店
            this.clubUsersLogic.autoAttentionShop(userId, magicGroup.getShopId());
            //核销拼团时自动绑定相应课程
            this.clubUsersLogic.autoSetClubUsersCourse(staffId, userId, magicGroup.getShopId(), courseId);

        }

        return ResponseObject.success();
    }

}
